<template>
  <div class="container">
    <div class="userinfo">
      <div class="user-avatar">
        <image :src="userAvatarUrl" mode="scaleToFill" lazy-load="true" />
      </div>
      <div class="user-name">
        <p>{{userNichName}}</p>
      </div>
      <div class="click-to-login" v-show="!alreadyLoginIn">
        <button
          class="btn"
          open-type="getUserInfo"
          lang="zh_CN"
          @getuserinfo="onGotUserInfo"
        ></button>
      </div>
    </div>

    <year-progress></year-progress>

    <button v-show="alreadyLoginIn" @click="scanBook">扫码添加图书</button>
  </div>
</template>

<script>
import YearProgress from '@/components/YearProgress.vue'
import { showSuccess, showMod, addBook } from '@/utils/index.js'

const db = wx.cloud.database()

// 用户点击拒绝的响应需要加上

export default {
  data () {
    return {
      alreadyLoginIn: false,
      userAvatarUrl: '../../../static/img/unlogin.png',
      userNichName: '请登录'
    }
  },

  methods: {
    onGotUserInfo (e) { // 点击登录
      const userInfo = e.mp.detail.userInfo
      // 先在数据库里面查是否已经有该用户
      // 没有则添加 有则存储本地
      db
        .collection('users')
        .where({
          _openid: userInfo._openid
        })
        .get()
        .then(res => {
          if (!res.data.length) {
            this.addUser(userInfo)
          } else {
            this.loginSuccess(res.data)
          }
        })
    },
    async addUser (data) { // 用户入库
      await db.collection('users')
        .add({
          data
        })
        .then(res => {
          this.loginSuccess(data)
        })
        .catch(console.error)
    },
    loginSuccess (userInfo) {
      wx.setStorageSync('__USER__', userInfo)
      showSuccess('登录成功')
      setTimeout(() => {
        this._initLogin()
      }, 15)
    },
    scanBook () { // 调用扫码
      wx.scanCode({
        success: res => {
          this.checkBook(res.result)
        },
        fail () {
          showMod({title: '错误', content: '扫码失败，请重试'})
        }
      })
    },
    checkBook (isbn) { // 检查数据库是否有该书籍
      db.collection('books').where({isbn})
        .get()
        .then(res => {
          if (!res.data.length) {
            addBook(isbn)
              .then()
          } else {
            showMod({title: '错误', content: '该书已上传，请换下一本'})
          }
        })
        .catch(err => console.error(err))
    },
    _initLogin () { // 初始化登录状态
      let storageUser = wx.getStorageSync('__USER__')
      if (!storageUser) {
        this.alreadyLoginIn = false
        return
      }
      this.alreadyLoginIn = true
      this.userAvatarUrl = storageUser[0].avatarUrl
      this.userNichName = storageUser[0].nickName
    }
  },

  mounted () {
    this._initLogin()
  },

  components: {
    YearProgress
  }
}
</script>

<style lang="stylus" scoped>
  .container
    padding 0 30rpx
    .userinfo
      position relative
      margin-top 100rpx
      padding-bottom 30rpx
      text-align center
      .user-avatar
        overflow hidden
        width 150rpx
        height 150rpx
        margin 0 auto 10rpx
        border-radius 50%
        image 
          width 100%
          height 100%
      .user-name
        font-size 32rpx
      .click-to-login
        .btn
          position absolute
          top 0
          left 0
          bottom 0
          right 0
          margin 0 auto
          padding 0
          width 40%
          height 100%
          opacity 0
</style>
